package common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.model.FileInformationBlock;
//文件上传类
public class UploadFileServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
	        String ymd = sdf.format(new Date());  
			String fName="";
			String fileName="";
			String saveUrl="uploads";
			saveUrl+="\\"+ymd+"\\";
			//上传文件的临时目录
			String tempDir=request.getSession().getServletContext().getRealPath("uploads");
			tempDir+="\\"+ymd+"\\";
			File tFile=new File(tempDir);
			if(!tFile.exists())
				tFile.mkdir();
			//创建缓冲区
			DiskFileItemFactory factory=new DiskFileItemFactory();
			
		    //设置缓冲区大小 1*1024*1024 设置1Mb
			factory.setSizeThreshold(1*1024*1024);
			//设置缓冲临时目录
			factory.setRepository(new File(tempDir));
			ServletFileUpload upload=new ServletFileUpload(factory); 
			//设置编码
			upload.setHeaderEncoding("UTF-8"); 
			response.setContentType("text/html;charset=utf-8");
			//设置文件最大值,这里设置5Mb,5*1024*1024;
			upload.setSizeMax(5*1024*1024);
			List<FileItem> list = upload.parseRequest(request);// 解析
				for(FileItem fi:list){
					if(!fi.isFormField()){
						fileName=fi.getName(); //获取文件名称
						String newFileName=UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
						saveUrl+=newFileName;
						fName=tempDir+newFileName; //文件最终存放目录
						File file=new File(fName);
						FileUtils.copyInputStreamToFile(fi.getInputStream(), file);
				}
			}
			response.getWriter().write(saveUrl+"_"+fileName);
		} catch (Exception e) {
			e.printStackTrace();
		     System.out.println(e.getMessage());
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response); //默认调用POST
	}
	

}